package com.changgou.search.controller;

import com.changgou.entity.Page;
import com.changgou.search.pojo.SkuInfo;
import com.changgou.search.service.SearchService;
import org.elasticsearch.action.termvectors.TermVectorsFilter;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.Map;
import java.util.Set;

@Controller
@RequestMapping("/search")
public class SearchController {
    @Autowired
    SearchService searchService;

    @GetMapping("/list")
    public String list(@RequestParam Map<String, String> searchMap, Model model) {
        this.handleSearchMap(searchMap);
        Map resultMap = searchService.search(searchMap);
        model.addAttribute("result", resultMap);
        model.addAttribute("searchMap", searchMap);
        //拼接url
        StringBuilder url = new StringBuilder("/search/list");
        // 如果有搜索条件
        if (searchMap != null && searchMap.size() > 0) {
            url.append("?");
            //拼接
            for (String paramKey : searchMap.keySet()) {
                //排除特殊情况
                if(!"sortRule".equals(paramKey)&&!"sortField".equals(paramKey)&&!"pageNum".equals(paramKey)){
                    url.append(paramKey).append("=").append(searchMap.get(paramKey)).append("&");
                }
            }

            String urlString = url.toString();
            //除去最后的&
            urlString=urlString.substring(0,urlString.length()-1);
            model.addAttribute("url", urlString);
        }else {
            model.addAttribute("url", url);
        }
        // 封装分页数据，并返回
        //总记录数
        // 当前页
        // 每页几条
        Page<SkuInfo> page = new Page<>(
                Long.parseLong(String.valueOf(resultMap.get("total"))),
                Integer.parseInt(String.valueOf(resultMap.get("pageNum"))),
                Page.pageSize
        );
        model.addAttribute("page", page);
        return "search";
    }


    @GetMapping
    @ResponseBody
    public Map search(@RequestParam Map<String, String> searchMap) {
        this.handleSearchMap(searchMap);
        ;
        Map searchResult = searchService.search(searchMap);
        return searchResult;
    }

    private void handleSearchMap(Map<String, String> searchMap) {
        Set<Map.Entry<String, String>> entries = searchMap.entrySet();
        for (Map.Entry<String, String> entry : entries) {
            if (entry.getKey().startsWith("spec_")) {
                searchMap.put(entry.getKey(), entry.getValue().replace("+", "%2B"));
            }
        }
    }
}
